<template>
  <div class="container">
    <a-space direction="vertical" size="large">
      <a-input-search
        v-model="inputIP"
        placeholder="请输入 IP 地址"
        @search="handleSearch"
        :style="{ width: '320px', display: 'flex', flexDirection: 'row' }"
      />
    </a-space>
    <!-- 显示结果界面 -->
    <div v-if="showResult || showDetailsPage">
      <ResultOk v-if="isSuccess" @showDetails="showDetails" />
      <ResultBad v-else @goBack="handleGoBack" />
      <div v-if="showDetailsPage">
        <p>IP 地址: {{ predictionResult.ip }}</p>
        <p>预测结果: {{ predictionResult.apt_group }}</p>
        <p>时间戳: {{ predictionResult.timestamp }}</p>
        <p>ASN:{{ predictionResult.asn }}</p>
        <p>asn_normalized:{{ predictionResult.asn_normalized }}</p>
        <p>asn_country_code:{{ predictionResult.asn_country_code}}</p>
        <p>asn_description:{{ predictionResult.asn_description }}</p>
      </div>
    </div>
    <!-- 默认展示数据列表 -->
    <div v-else>
      <a-divider style="margin-top: 16px" />
      <a-table
        :loading="loading"
        :columns="columns"
        :data="ipList"
        :bordered="false"
        @change="handleChange"
      >
        <template #used_ip="{ record }">
          <span :style="{ color: '#FEFFF0' }">{{ record.used_ip }}</span>
        </template>
        <template #asn="{ record }">
          <span :style="{ color: getColor(record.asn) }">{{ record.asn }}</span>
        </template>
        <template #asnCountryCode="{ record }">
          <span :style="{ color: getColor(record.asn) }">{{ record.asnCountryCode }}</span>
        </template>
        <template #asnDescription="{ record }">
          <span :style="{ color: getColor(record.asn) }">{{ record.asnDescription }}</span>
        </template>
        <template #apt_group="{ record }">
          <span :style="{ color: getColor(record.apt_group) }">{{ record.apt_group }}</span>
        </template>
        <template #apt_group-filter="{ filterValue, setFilterValue, handleFilterConfirm, handleFilterReset}">
          <div class="custom-filter">
            <a-space direction="vertical">
              <a-input :model-value="filterValue[0]" @input="(value)=>setFilterValue([value])" />
              <div class="custom-filter-footer">
                <a-button @click="handleFilterConfirm">Confirm</a-button>
                <a-button @click="handleFilterReset">Reset</a-button>
              </div>
            </a-space>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import axios from 'axios';
import { h } from 'vue';
import { IconSearch } from '@arco-design/web-vue/es/icon';
import ResultOk from './resultok.vue';
import ResultBad from './resultbad.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const inputIP = ref('');
const loading = ref(false);
const ipList = ref([]);
const predictionResult = ref(null);
const showResult = ref(false);
const isSuccess = ref(false);
const showDetailsPage = ref(false);

const colors = [
  '#FFE8F1', '#F756A9', '#B01BB6', '#7B3DD1', '#306FFF', '#93BEFF', '#C59AED', '#F092E6', '#7DC1FC',
  '#469AFA', '#66DFD7', '#11838B', '#1DB440', '#B2F0B7', '#84B723', '#FBE94B', '#FEFEC6', '#4D2D00',
  '#FFB357', '#F9925A', '#CB2E34', '#770611'
];
const colorMap = new Map();

const columns = computed<TableColumnData[]>(() => [
  {
    title: '使用的 IP',
    dataIndex: 'used_ip',
    slotName: 'used_ip',
    width: 150
  },
  {
    title: 'ASN',
    dataIndex: 'asn',
    slotName: 'asn',
    width: 150
  },
  {
    title: 'ASN 国家代码',
    dataIndex: 'asnCountryCode',
    slotName: 'asnCountryCode',
    width: 150
  },
  {
    title: 'ASN 描述',
    dataIndex: 'asnDescription',
    slotName: 'asnDescription',
    width: 250
  },
  {
    title: 'APT 组织',
    dataIndex: 'apt_group',
    slotName: 'apt_group',
    width: 150,
    filterable: {
      filter: (value, record) => record.apt_group.includes(value),
      slotName: 'apt_group-filter',
      icon: () => h(IconSearch)
    }
  },
]);

const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get('http://localhost:3001/api/used-ip-details');
    console.log('response.data:', response.data);
    ipList.value = response.data.data;
    colorMap.clear();
  } catch (err) {
    console.error('Error fetching data:', err);
    console.error('Error response:', err.response);
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  if (inputIP.value) {
    try {
      const response = await axios.post('http://localhost:5001/ip-predict', {
        ip: inputIP.value
      });
      predictionResult.value = response.data;
      isSuccess.value = true;
    } catch (err) {
      console.error('Error predicting IP:', err);
      predictionResult.value = null;
      isSuccess.value = false;
    }
    showResult.value = true;
    showDetailsPage.value = false;
  }
  await fetchData();
};

const handleChange = (data, extra, currentDataSource) => {
  console.log('change', data, extra, currentDataSource);
};

const getColor = (value) => {
  if (!colorMap.has(value)) {
    const index = colorMap.size % colors.length;
    colorMap.set(value, colors[index]);
  }
  return colorMap.get(value);
};

const showDetails = () => {
  const encodedResult = encodeURIComponent(JSON.stringify(predictionResult.value));
  router.push({
    name: 'IpResultDetail',
    params: {
      predictionResult: encodedResult
    }
  });
  // showDetailsPage.value = true;
  // showResult.value = false;
};

const handleGoBack = () => {
  showResult.value = false;
  showDetailsPage.value = false;
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}

:deep(.arco-table-th) {
  background-color: #2e2e30;
  color: #f6f6f6;
}
:deep(.arco-table-td) {
  background-color: #232324;
  color: #f6f6f6;
}
:deep(.arco-table-tr:hover),
:deep(.arco-table-tr:hover) > td {
  background-color: #3a3a3d !important;
}

.circle {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.circle::before {
  content: '';
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.red::before {
  background-color: #f5222d;
}

.green::before {
  background-color: #52c41a;
}

.circle:hover {
  color: #ff9900;
}

.red:hover::before {
  background-color: #ff6666;
}

.green:hover::before {
  background-color: #99ff66;
}

.custom-filter {
  padding: 20px;
  background: var(--color-bg-5);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 2px 5px rgb(0 0 0 / 10%);
}

.custom-filter-footer {
  display: flex;
  justify-content: space-between;
}
</style>